//
//  OrderInHand1ViewController.m
//  OrderApp1
//
//  Created by trimad on 11-10-27.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import <QuartzCore/QuartzCore.h>
#import "OrderInHandViewController.h"
#import "CoverViewController.h"
#import "Util.h"
#import "ContextManager.h"
#import "MenuViewController.h"
#import "PageViewController.h"
#import "GlobalFlavor.h"
#import "OrderManager.h"
#import "DishFlavor.h"


@implementation OrderInHandViewController

@synthesize coverViewController;
@synthesize orderTableData;
@synthesize totalQuantity;
@synthesize totalPrice;
@synthesize orderTableView;


// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        
    }
    return self;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	UIColor *tableBackgroundColor = [UIColor colorWithRed:(CGFloat)247/255 
										   green:(CGFloat)245/255 
											blue:(CGFloat)234/255 
										   alpha:(CGFloat)1.0];
	[orderTableView setBackgroundColor:tableBackgroundColor];
	
	NSMutableDictionary *tempDic=[Util readFileForDictionary:@"localOrderData"];
	NSLog(@"tempDictionary is: %@ ",tempDic);
	orderTableData=tempDic;
	
	NSArray *valueArray=[orderTableData allValues];
	int tempTotalQuantity=0;
	double tempTotalPrice=0.0;
	for(int i=0;i<[valueArray count];i++){
		NSMutableArray *tempMutableArray=(NSMutableArray *)[valueArray objectAtIndex:i];	
		NSString *tpQuantity=[tempMutableArray objectAtIndex:1];
		tempTotalQuantity=tempTotalQuantity+[tpQuantity intValue];
		NSString *tpPrice=[tempMutableArray objectAtIndex:2];
		tempTotalPrice=tempTotalPrice+[tpQuantity intValue] * [tpPrice floatValue];
	}

	totalQuantity.text=[NSString stringWithFormat:@"%i",tempTotalQuantity];
	totalPrice.text=[NSString stringWithFormat:@"%.2f",tempTotalPrice];
}



- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    return YES;
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}


- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[coverViewController release];
	[orderTableData release];
	[totalQuantity release];
	[totalPrice release];
    [super dealloc];
}

- (IBAction)completeOrder:(id)sender{
	NSLog(@"completeOrder");
	self.view.superview.hidden=YES;
	if ([self.view.superview.superview 
			isEqual:[ContextManager getInstance].rootViewController.view]) {
		[self.view.superview.superview removeFromSuperview];
	}
	//save order
	//Order *currentOrder=[Util getOrderFromService];
	//[Util SaveOrderFromService:currentOrder];
}

- (IBAction)closeOrderInHand:(id)sender{
	NSLog(@"closeOrderInHand");
	self.view.superview.hidden=YES;
}

#pragma mark -
#pragma mark Table View Data Source Methods

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
	return [self.orderTableData count];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier";
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier];
	if (cell == nil) {
		cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle
									  reuseIdentifier:SimpleTableIdentifier] autorelease];
	}
	UIColor *tableBackgroundColor = [UIColor colorWithRed:(CGFloat)247/255 
													green:(CGFloat)245/255 
													 blue:(CGFloat)234/255 
													alpha:(CGFloat)1.0];
	NSUInteger row1=[indexPath row];
	NSArray *keyArray=[orderTableData allKeys];
	NSArray *valueArray=[orderTableData allValues];
	int itemCode=[(NSString *)[keyArray objectAtIndex:row1] intValue];
	NSMutableArray *tempMutableArray=(NSMutableArray *)[valueArray objectAtIndex:row1];
	
	UIButton * deleteButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0,40, 40)];
	[deleteButton setTag:row1];
	[deleteButton addTarget:self action:@selector(deleteOrderItem:) forControlEvents:UIControlEventTouchDown];
	[cell.contentView addSubview:deleteButton];
	[deleteButton release];
	
	UIImage *tempImage=[UIImage imageNamed:@"wrong.png"];
	cell.imageView.image=tempImage;

	NSString *tempStr=@"x";
	
	UILabel *dishNameLabel=[[UILabel alloc] initWithFrame:CGRectMake(40, 0, 160, 40)];
	dishNameLabel.text=[tempMutableArray objectAtIndex:0];
	dishNameLabel.backgroundColor = tableBackgroundColor;
	[cell addSubview:dishNameLabel];
	
	UILabel *dishPriceLabel=[[UILabel alloc] initWithFrame:CGRectMake(200, 0, 70, 40)];
	dishPriceLabel.text=[tempMutableArray objectAtIndex:2];
	dishPriceLabel.backgroundColor = tableBackgroundColor;
	[cell addSubview:dishPriceLabel];	
	
	UILabel *dishQuantityLabel=[[UILabel alloc] initWithFrame:CGRectMake(290, 0, 30, 40)];
	tempStr=[tempStr stringByAppendingString:[tempMutableArray objectAtIndex:1]];
	dishQuantityLabel.text=tempStr;
	dishQuantityLabel.backgroundColor = tableBackgroundColor;
	[cell addSubview:dishQuantityLabel];
	[cell addSubview:dishNameLabel];
	
	UIButton * flavorButton = [[UIButton alloc] initWithFrame:CGRectMake(320, 5, 11, 25)];
	UIImage *tempImage2=[UIImage imageNamed:@"bottom-img-right_3.png"];
	[flavorButton setBackgroundImage:tempImage2 forState:UIControlStateNormal];
	[flavorButton setTag:itemCode];
	[flavorButton addTarget:self action:@selector(setFlavor:) forControlEvents:UIControlEventTouchDown];
	[cell.contentView addSubview:flavorButton];
	[flavorButton release];
	[cell setBackgroundColor:tableBackgroundColor];
	
	return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
	NSLog(@"didSelectRowAtIndexPath");
	NSUInteger row1=[indexPath row];
	NSArray *valueArray=[orderTableData allValues];
	NSMutableArray *tempMutableArray=(NSMutableArray *)[valueArray objectAtIndex:row1];	
	int pageIndex=[[tempMutableArray objectAtIndex:3] intValue];
	MenuViewController *menuVC=[[ContextManager getInstance] rootViewController];
	[menuVC jumpToPage:pageIndex];
}

- (IBAction)refresh:(id)sender{
	NSLog(@"refresh");
	NSMutableDictionary *tempDic=[Util readFileForDictionary:@"localOrderData"];
	NSLog(@"tempDictionary is: %@ ",tempDic);
	orderTableData=tempDic;
	[orderTableView reloadData];
	
	NSArray *valueArray=[orderTableData allValues];
	int tempTotalQuantity=0;
	double tempTotalPrice=0.0;
	for(int i=0;i<[valueArray count];i++){
		NSMutableArray *tempMutableArray=(NSMutableArray *)[valueArray objectAtIndex:i];	
		NSString *tpQuantity=[tempMutableArray objectAtIndex:1];
		tempTotalQuantity=tempTotalQuantity+[tpQuantity intValue];
		NSString *tpPrice=[tempMutableArray objectAtIndex:2];
		tempTotalPrice=tempTotalPrice+[tpQuantity intValue] * [tpPrice floatValue];
	}
	
	totalQuantity.text=[NSString stringWithFormat:@"%i",tempTotalQuantity];
	totalPrice.text=[NSString stringWithFormat:@"%.2f",tempTotalPrice];
}

- (IBAction)deleteOrderItem:(id)sender{
	NSLog(@"deleteOrderItem");
	UIButton *uiButton=(UIButton *)sender;
	NSUInteger rowId = uiButton.tag;
	
	NSString *itemCode = [[orderTableData allKeys] objectAtIndex:rowId];
	[orderTableData removeObjectForKey:itemCode];
	[orderTableView reloadData];
	[Util writeFileForDictionary:orderTableData:@"localOrderData"];
	[[OrderManager getInstance] removeOrderItem:itemCode];
	[self refresh:nil];
}

- (IBAction)setGlobalOptions:(id)sender{
	NSLog(@"setGlobalOptions");
	GlobalFlavor *globalFlavor=[[GlobalFlavor alloc] initWithNibName:@"GlobalFlavor" bundle:nil];
	[self.view addSubview:globalFlavor.view];
}

- (IBAction)setFlavor:(id)sender{
	NSLog(@"setFlavor");
	UIButton *uiButton=(UIButton *)sender;
	NSUInteger rowId = uiButton.tag;
	
	NSString *itemCode = [[orderTableData allKeys] objectAtIndex:rowId];
	DishFlavor *dishFlavor=[[DishFlavor alloc] initWithNibName:@"DishFlavor" bundle:nil item:itemCode];
	[self.view addSubview:dishFlavor.view];
}

@end

